package selef.xiafan.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import selef.xiafan.dao.*;
import selef.xiafan.entity.Customer;
import selef.xiafan.entity.order.Order;
import selef.xiafan.entity.order.OrderCustomer;
import selef.xiafan.entity.order.OrderItem;
import selef.xiafan.entity.order.Settlement;
import selef.xiafan.entity.system.Stock;
import selef.xiafan.query.SettlementQuery;
import selef.xiafan.service.ISettleMentService;
import selef.xiafan.util.result.PageResult;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * @author xiafan
 * @version 1.0
 * @date 2021/8/1 8:01
 */
@Service
public class ISettleMentServiceImpl implements ISettleMentService {
    @Autowired
    SettleMentDao settleMentDao;
    @Autowired
    OrderCustomerDao orderCustomerDao;
    @Autowired
    CustomerDao customerDao;
    @Autowired
    OrderDao orderDao;
    @Autowired
    OrderItemDao orderItemDao;
    @Autowired
    StockDao stockDao;

    @Override
    public PageResult<Settlement> settlementList(SettlementQuery settlementQuery) {
        Integer page = (settlementQuery.getPage() - 1) * settlementQuery.getSize();
        Integer size = settlementQuery.getSize();
        String nameForQuery = settlementQuery.getName();
        String carForQuery = settlementQuery.getCarNum();

        /**  不携带参数查询时  */
        if (nameForQuery == "" && carForQuery == "") {
            Long total = settleMentDao.countAll();
            if (total != 0L) {
                List<Settlement> settlementList = settleMentDao.findAllNoQuery(page, size)
                        .stream().distinct().collect(Collectors.toList());
                List<Settlement> settleList = new ArrayList<>();
                for (Settlement settlement : settlementList) {
                    // 根据订单id查询订单信息
                    Order byOrderId = orderDao.findByOrderId(settlement.getOrderId());
                    // 获取客户信息
                    OrderCustomer byOrderId1 = orderCustomerDao.findByOrderId(byOrderId.getOrderId());
                    Customer customer = customerDao.findById(byOrderId1.getCustomerId()).get();
                    // 获取订单明细
                    List<OrderItem> OrderItemList = orderItemDao.findAllByOrderId(byOrderId1.getOrderId());
                    List<OrderItem> orderItems = new ArrayList<>();
                    for (OrderItem orderItem : OrderItemList) {
                        // 获取服务信息
                        String stockId = orderItem.getStockId();
                        Stock byStockId = stockDao.findByStockId(stockId);
                        // 将BigDecimal转为Int类型进行计算，数量*预售价
                        BigDecimal sellPrice = byStockId.getSellPrice();

                        orderItem.setPrice(sellPrice.multiply(BigDecimal.valueOf(orderItem.getStockNum())));
                        orderItem.setStockName(byStockId.getName());
                        orderItems.add(orderItem);
                    }
                    settlement.setAddress(byOrderId.getAddress());
                    settlement.setOrderItem(orderItems);
                    settlement.setOrder(byOrderId);
                    settlement.setCustomer(customer);
                    settleList.add(settlement);

                }
                return new PageResult<>(total, settleList);
            } else {
                return new PageResult<>();
            }
        }
        /** 携带参数查询时 */
        // 1.数据总量为查询到的订单数量
        Long total = customerDao.countWithQuery(nameForQuery, carForQuery); // 该方法在只有条件查询生效，模糊查询无效

        if (total == 0L) {
            return new PageResult<>();
        }
        List<Settlement> settlementList = settleMentDao.findAllWithQuery(page, size, nameForQuery, carForQuery)
                .stream().distinct().collect(Collectors.toList());
        List<Settlement> settleList = new ArrayList<>();
        for (Settlement settlement : settlementList) {
            // 根据订单id查询订单信息
            Order byOrderId = orderDao.findByOrderId(settlement.getOrderId());
            // 获取客户信息
            OrderCustomer byOrderId1 = orderCustomerDao.findByOrderId(byOrderId.getOrderId());
            Customer customer = customerDao.findById(byOrderId1.getCustomerId()).get();
            // 获取订单明细
            List<OrderItem> OrderItemList = orderItemDao.findAllByOrderId(byOrderId1.getOrderId());
            List<OrderItem> orderItems = new ArrayList<>();
            for (OrderItem orderItem : OrderItemList) {
                // 获取服务信息
                String stockId = orderItem.getStockId();
                Stock byStockId = stockDao.findByStockId(stockId);
                // 将BigDecimal转为Int类型进行计算，数量*预售价
                BigDecimal sellPrice = byStockId.getSellPrice();

                orderItem.setPrice(sellPrice.multiply(BigDecimal.valueOf(orderItem.getStockNum())));
                orderItem.setStockName(byStockId.getName());
                orderItems.add(orderItem);
            }

            settlement.setOrderItem(orderItems);
            settlement.setOrder(byOrderId);
            settlement.setCustomer(customer);
            settleList.add(settlement);

        }
        return new PageResult<>(total, settleList);
        // 1.根据客户姓名与车牌号查询客户信息
        // 2.根据客户信息查询关联表信息
        // 3.查询结算信息
    }

    /**
     * 在订单完成服务提交时调用该方法
     *
     * @param order     订单信息
     * @param orderItem 订单详情
     */
    @Override
    public Integer save(Order order, List<OrderItem> orderItem) {
        // 对使用的配件/服务进行数量删减
         for (OrderItem item : orderItem) {
             // 根据配件/服务id查询信息
             Stock stockInDb = stockDao.findByStockId(item.getStockId());
             stockInDb.setRemainAmount(stockInDb.getRemainAmount() - item.getStockNum());
             stockDao.save(stockInDb);
         }
        String substring = "s" + UUID.randomUUID().toString().substring(0, 6);
        Settlement settleMent = new Settlement();
        // 查询生成的id在数据库中是否有重复
        Settlement bySettleId = settleMentDao.findBySettleId(substring);
        if (bySettleId != null) {
            if (substring.equals(bySettleId.getSettleId())) {
                return 2;// 请重新提交
            }
        }
        settleMent.setSettleId(substring);
        settleMent.setOrderId(order.getOrderId());
        settleMent.setStatus(false);// 默认未结算
        settleMentDao.save(settleMent);
        return 1;
    }

    /*
     * 功能：
     * 确认支付后修改两个状态：1订单状态（5归还中：当订单需要归还时, 6完成订单：当订单不需要归还时），2支付状态
     * */
    @Override
    public Integer confirmPay(Settlement requestSettlement) {
        Order orderInDbByOrderId = orderDao.findByOrderId(requestSettlement.getOrderId());
        if (orderInDbByOrderId.getIsReturn() == 0) { // 不需要还车时
            orderInDbByOrderId.setStatus(6);
        }
        if (orderInDbByOrderId.getIsReturn() == 1) { // 需要还车时
            orderInDbByOrderId.setStatus(5);
        }
        // 当前订单客户为VIP时进行折扣
        if (requestSettlement.getCustomer().getIsVip()) {
            BigDecimal discount = BigDecimal.valueOf(0.8);
            BigDecimal totalPrice = requestSettlement.getOrder().getTotalPrice();
            requestSettlement.getOrder().setTotalPrice(discount.multiply(totalPrice));
        }

        orderDao.save(orderInDbByOrderId);
        requestSettlement.setStatus(true);
        requestSettlement.setType(requestSettlement.getType());
        settleMentDao.save(requestSettlement);
        return 1; // 确认支付
    }
}
